package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 统计指定时间区间内的营业额
     * 营业额：状态为 完成 的 订单 orders总金额
     *
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        // 这个集合用于存储从begin到end，包含两头，的每天的日期
        // 日期比较是否相等可以使用equals

        List<LocalDate> dateList = getDateList(begin, end);

        // 存放每天的营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            // 遍历每天，查询每天的营业额，放到集合当中
            // 使用of方法把localDate和localTime组装成localDateTime
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            // 使用map传递参数
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begin", beginTime);
            map.put("end", endTime);

            Double turnover = orderMapper.sumByMap(map);
            // 如果当天营业额为0，返回的是Null,手动转成0.0
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 统计指定时间内的用户数据
     *
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        // 日期
        List<LocalDate> dateList = getDateList(begin, end);
        // 新用户集合
        List<Integer> newUserList = new ArrayList<>();
        // 总用户数集合
        List<Integer> totalUserList = new ArrayList<>();

        for (LocalDate localDate : dateList) {
            LocalDateTime min = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime max = LocalDateTime.of(localDate, LocalTime.MAX);

            // 截止到当天的总用户 create_time < max
            Map map = new HashMap();
            map.put("end", max);
            Integer total = userMapper.countByMap(map);
            totalUserList.add(total);

            // 每天新增用户数量  create_time > min && create_time < max
            map.put("begin", min);
            Integer newUser = userMapper.countByMap(map);
            newUserList.add(newUser);
        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    private static List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList();

        dateList.add(begin);

        while (!begin.equals(end)) {
            // 计算指定日期后一天的日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //日期，以逗号分隔，例如：2022-10-01,2022-10-02,2022-10-03
        //private String dateList;
        List<LocalDate> dateList = getDateList(begin, end);

        // 订单总数  orderCountList
        List<Integer> orderCountList = new ArrayList<>();

        // 有效订单数  validOrderCountList
        List<Integer> validOrderCountList = new ArrayList<>();

        for (LocalDate localDate : dateList) {
            //每日订单数，以逗号分隔，例如：260,210,215
            //private String orderCountList;
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            Map map = new HashMap();

            map.put("begin", beginTime);
            map.put("end", endTime);

            // select count(id) from orders where order_time > beginTime and order_time < endTime
            Integer orderCount = orderMapper.getOrdersSumByDate(map);
            orderCountList.add(orderCount);

            //每日有效订单数，以逗号分隔，例如：20,21,10
            //private String validOrderCountList;
            // select count(id) from orders
            // where status = 5 and order_time > beginTime and order_time < endTime
            map.put("status", Orders.COMPLETED);
            Integer validOrderCount = orderMapper.getOrdersSumByDate(map);
            validOrderCountList.add(validOrderCount);
        }

        //订单总数
        //private Integer totalOrderCount;
        // 第一天的最早时间
        LocalDateTime start = LocalDateTime.of(begin, LocalTime.MIN);
        // 最后一天的最后时间
        LocalDateTime tail = LocalDateTime.of(end, LocalTime.MAX);
        Map map = new HashMap();
        map.put("begin", start);
        map.put("end", tail);
//        Integer totalOrderCount = orderMapper.getOrdersSum(map);
        // 使用Stream流简化书写
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();

        //有效订单数
        //private Integer validOrderCount;
        map.put("status", Orders.COMPLETED);
//        Integer validOrderCount = orderMapper.getOrdersSum(map);
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //订单完成率
        //private Double orderCompletionRate;totalOrderCount

        // 注意类型转换
        // 防止total为0

        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(StringUtils.join(orderCountList, ","))
                .build();
    }

    /**
     * 统计指定时间范围内的销量Top10产品
     *
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        // 统计指定时间范围内销量排名前10的菜品或套餐
        // 第一天的最早时间
        LocalDateTime start = LocalDateTime.of(begin, LocalTime.MIN);
        // 最后一天的最后时间
        LocalDateTime tail = LocalDateTime.of(end, LocalTime.MAX);

        // 统计指定时间范围内销量排名前10的菜品名称及数量
        List<GoodsSalesDTO> salesTop10List = orderMapper.getSalesTop10(start, tail);
        // 使用Stream流简化
        List<String> names = salesTop10List.stream().map(GoodsSalesDTO::getName).toList();
        List<Integer> numbers = salesTop10List.stream().map(GoodsSalesDTO::getNumber).toList();

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(names, ","))
                .numberList(StringUtils.join(numbers, ","))
                .build();
    }

    /**
     * 导出运营数据报表
     *
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        // 1.查询数据库，获得营业数据 - 查询最近30天的运营数据

        LocalDate beginTime = LocalDate.now().minusDays(30);
        LocalDate endTime = LocalDate.now().minusDays(1);

        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(beginTime, LocalTime.MIN), LocalDateTime.of(endTime, LocalTime.MAX));

        // 2.将查询到的数据写入到Excel文件
        // 类路径下的表格模版
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            // 使用Excel模板创建一份新的Excel文件
            XSSFWorkbook sheets = new XSSFWorkbook(is);
            // 获取info标签页
            XSSFSheet sheet = sheets.getSheetAt(0);
            // 先写入日期
            sheet.getRow(1).getCell(1).setCellValue("时间：" + beginTime + " 至 " + endTime);
            // 写入概览数据
            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());

            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());

            // 设置明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = beginTime.plusDays(i);

                // 查询某一天的营业数据
                BusinessDataVO businessData1 = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                // 写入到Excel
                sheet.getRow(7 + i).getCell(1).setCellValue(date.toString());
                sheet.getRow(7 + i).getCell(2).setCellValue(businessData1.getTurnover());
                sheet.getRow(7 + i).getCell(3).setCellValue(businessData1.getValidOrderCount());
                sheet.getRow(7 + i).getCell(4).setCellValue(businessData1.getOrderCompletionRate());
                sheet.getRow(7 + i).getCell(5).setCellValue(businessData1.getUnitPrice());
                sheet.getRow(7 + i).getCell(6).setCellValue(businessData1.getNewUsers());
            }

            // 3.通过输出流把报表文件下载到客户端浏览器
            ServletOutputStream os = response.getOutputStream();
            sheets.write(os);

            // 释放资源
            sheets.close();
            os.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
